package com.chen.base.module.redis.service.impl;

import com.chen.base.module.redis.inter.LockFunctional;
import com.chen.base.module.redis.service.DistributedLock;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author: Long
 * @date: 2023/5/3 18:27
 **/
@Service
@Slf4j
public class RedissonDistributedLock implements DistributedLock<RLock> {

    @Resource
    private RedissonClient redissonClient;

    @Override
    @SneakyThrows
    public LockFunctional lock(String key, long expire) {
        // 定义锁
        RLock lock = redissonClient.getLock(key);
        // 尝试加锁，10秒等待，expire锁时间
        boolean tryLock = lock.tryLock(10000, expire, TimeUnit.MILLISECONDS);
        return tryLock ? () -> unLock(lock) : null;
    }

    @Override
    @SneakyThrows
    public Boolean unLock(RLock lockObj) {
        if (lockObj != null && lockObj.isLocked() && lockObj.isHeldByCurrentThread()){
            lockObj.unlock();
            return true;
        }
        return false;
    }

}
